package com.atguigu.dga.meta.controller;

import com.atguigu.dga.meta.bean.TableMetaInfo;
import com.atguigu.dga.meta.bean.TableMetaInfoExtra;
import com.atguigu.dga.meta.bean.TableMetaInfoQuery;
import com.atguigu.dga.meta.bean.TableMetaInfoVO;
import com.atguigu.dga.meta.service.TableMetaInfoExtraService;
import com.atguigu.dga.meta.service.TableMetaInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author zhangchen
 * @since 2024-11-19
 */
@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {

    @Autowired
    TableMetaInfoService tableMetaInfoService;

    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;

    @GetMapping("/table-list")
    public Map getTableList(TableMetaInfoQuery tableMetaInfoQuery) throws Exception{

        List<TableMetaInfoVO> list = tableMetaInfoService.getTableMetaForQuery(tableMetaInfoQuery);
        Integer total= tableMetaInfoService.getTableMetaTotalForQuery(tableMetaInfoQuery);
        Map resultMap=new HashMap();
        resultMap.put("total",total);
        resultMap.put("list",list);

        return resultMap;
    }

    @GetMapping("/table/{tableId}")
    public TableMetaInfo getTableMeta(@PathVariable("tableId") Long tableId){
        TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(tableId);

        TableMetaInfoExtra tableMetaInfoExtra = tableMetaInfoExtraService.getOne(new QueryWrapper<TableMetaInfoExtra>()
                .eq("table_name", tableMetaInfo.getTableName())
                .eq("schema_name", tableMetaInfo.getSchemaName()));

        tableMetaInfo.setTableMetaInfoExtra(tableMetaInfoExtra);

        return tableMetaInfo;
    }

    @PostMapping("/tableExtra")
    public String saveTableExtra(@RequestBody TableMetaInfoExtra    tableMetaInfoExtra){
        tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra);
        return  "success";
    }

    @PostMapping("/init-tables/{schemaName}/{assessDate}")
    public String initTables(@PathVariable("schemaName") String schemaName,
                            @PathVariable("assessDate") String assessDate) throws Exception{
        tableMetaInfoService.extractMetaData(schemaName,assessDate);
        return "success";
    }

}
